<?php

namespace teach\controllers;

use teach\service\Streaming;
use teach\util\helper\ResponseHelper;
use Yii;
use yii\filters\Cors;
use yii\rest\ActiveController;
use yii\web\Response;

class StreamingController extends ActiveController
{
    public $modelClass = '';

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
        $behaviors['corsFilter'] = [
            'class' => Cors::class,
            'cors' => [
                'Origin' => ['*'],
                'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
                'Access-Control-Request-Headers' => ['*'],
                'Access-Control-Allow-Credentials' => true,
                'Access-Control-Max-Age' => 86400,
            ],
        ];
        return $behaviors;
    }

    //接收flink转发的kafka消息
    public function actionKafka()
    {
        //$request = Yii::$app->request;
        //$data = $request->post();
        $post = file_get_contents("php://input");
        $data = json_decode($post, true);
        //var_dump($data);

        $msg = "";
        $flag = false;
        if (!$data) {
            $msg = "没有获取到data";
        } else {
            $flag = true;
        }

        if (!$flag) {
            $jsonData = ResponseHelper::buildJsonData(400, $msg);
        } else {
            $streaming = new Streaming();
            $state = $data['state'];
            $message = $data['message'];
            //var_dump($data);
            //exit();
            switch ($state) {
                case 1:
                    $result = $streaming->deliverGoods($message);//小程序发送消息告诉用户已经发货
                    break;
                default:
                    $result = "没有匹配的类型";
                    break;
            }
            $jsonData = ResponseHelper::buildJsonData(200, "成功", $result);
        }
        return $this->asJson($jsonData);
    }
}